#!/usr/bin/env python
# coding: utf-8

# In[1]:


# 加载自带的手写数字识别的数据集
from keras.datasets import mnist

(X_train, Y_train), (X_test, Y_test) = mnist.load_data()
print(type(X_train), X_train.shape)

# In[3]:


# 可视化部分数据
import matplotlib.pyplot as plt

img1 = X_train[0]
fig1 = plt.figure(figsize=(3, 3))
plt.imshow(img1)
plt.title(Y_train[0])
plt.show()

# In[4]:


img1.shape

# In[11]:


# 格式化输入数据
feature_size = img1.shape[0] * img1.shape[1]
# print(feature_size)
X_train_format = X_train.reshape(X_train.shape[0], feature_size)
X_test_format = X_test.reshape(X_test.shape[0], feature_size)
print(X_train_format.shape, X_test_format.shape)

# In[14]:


# 输入数据归一化
X_train_normal = X_train_format / 255
X_test_normal = X_test_format / 255
print(X_train_format[0])
print(X_train_normal[0])

# In[23]:


# 格式化输出数据
from keras.utils.np_utils import to_categorical

Y_train_format = to_categorical(Y_train)
Y_test_format = to_categorical(Y_test)
print(Y_train[0], Y_train_format[0])

# In[26]:


# 建立模型结构
from keras.models import Sequential
from keras.layers import Dense, Activation

mlp_model = Sequential()
mlp_model.add(Dense(units=392, activation='sigmoid', input_dim=feature_size))
mlp_model.add(Dense(units=392, activation='sigmoid'))
mlp_model.add(Dense(units=10, activation='softmax'))  # softmax多分类
mlp_model.summary()

# In[27]:


# 配置模型
mlp_model.compile(loss='categorical_crossentropy', optimizer='adam')

# In[28]:


# 模型训练
mlp_model.fit(X_train_normal, Y_train_format, epochs=10, verbose=1)

# In[36]:


# 模型评估
import numpy as np

Y_train_predict = np.argmax(mlp_model.predict(X_train_normal), axis=1)
# print(Y_train_predict)
from sklearn.metrics import accuracy_score

print(accuracy_score(Y_train, Y_train_predict))

# In[38]:


Y_test_predict = np.argmax(mlp_model.predict(X_test_normal), axis=1)
print(accuracy_score(Y_test, Y_test_predict))

# In[48]:


i = 16
img2 = X_test[i]
fig2 = plt.figure(figsize=(3, 3))
plt.imshow(img2)
plt.title(Y_test_predict[i])
plt.show()
